<?php

namespace app\company\admin;
use app\admin\controller\Admin;
use app\common\builder\ZBuilder;
use app\company\model\Company as CompanyModel;
use app\pipeline\model\Business as BusinessModel;
use app\pipeline\model\Equipment as EquipmentModel;
use app\user\model\User;

class Index extends Admin
{
     //公司列表
    public function index(){
        $map=$this->getMap();
        if($this->user_auth['role']!==1){
            $map[]=['b_company','=',$this->user_auth['company_id']];
        }
        $data_list = CompanyModel::where($map)->order('id','desc')->paginate()->each(function($value){
            $value['company_type']=$value['company_type'] == 'third' ? "第三方机构" : ($value['company_type'] == 'third_slave' ? "委托类公司" : "自检管道公司");
        });
        return ZBuilder::make('table')
            ->setPageTitle('公司管理') // 页面标题
            ->setTableName('company') // 设置表名
            ->setSearch(['name' => '公司名称', 'id' => 'ID']) // 设置搜索参数
            ->addColumns([ // 批量添加列
                ['id', 'ID'],
                ['name', '公司名称'],
                ['address', '公司地址'],
                ['company_type','公司类型'],
                ['description', '描述'],
                ['create_time', '创建时间'],
                ['update_time', '修改时间'],
                ['right_button', '操作', 'btn']
            ])
            ->addRightButtons(
                [
                    'edit'=> ['title'=>'编辑','href' => url('company_save', ['id' => '__id__'])],
                    'delete'=>['title'=>'删除','href'=>url('company_del',['id'=>'__id__'])]
                ]
            )
            ->addTopButton('add',['href'=>url('company_save')])
            ->setRowList($data_list) // 设置表格数据
            ->fetch(); // 渲染模板
    }

    //添加公司
    public function company_save(){
        $id=$this->request->param('id');
        if($this->request->isPost()){
            $data=$this->request->post();

            if($this->user_auth['role']!==1){
                $data['b_company']=$this->user_auth['company_id'];
                $data['company_type']='third_slave';
            }
            if($data['company_type']=='third_slave'&&empty($data['b_company'])){
                $this->error('公司为委托类公司时,第三方机构不能为空');
            }
            //验证
            $result = $this->validate($data, 'Company');
            if(true !== $result) $this->error($result);
            $has_name=CompanyModel::where('name',$data['name'])->value('id');
            if($has_name){
                if(!empty($id)){
                    if($has_name!=$id){
                        $this->error('修改失败,已存在相同公司名称');
                    }
                }else{
                    $this->error('添加失败,已存在相同公司名称');
                }
            }
            if(!empty($id)){
                $result=CompanyModel::update($data);
                action_log('company_edit', 'company', $data['id'], UID, json_encode($data,JSON_UNESCAPED_UNICODE));
            }else{
                $result=CompanyModel::create($data);
                action_log('company_add', 'company', $result['id'], UID, $data['name']);
            }
            if(!$result){
                $this->error('添加失败');
            }

            $this->success('编辑成功','index');
        }

        $info=CompanyModel::get($id);
        $company_type=config('company_type');
        // 显示编辑页面
        $zbuilder=ZBuilder::make('form')
            ->setPageTitle('编辑公司信息')
            ->setPageTips('请谨慎操作','warning')
            ->addFormItems([
                ['hidden', 'id'],
                ['text', 'name', '公司名称', '<span class="text-danger">必填</span>'],
                ['text', 'address', '公司地址', '<span class="text-danger">必填</span>'],
            ]);
        //管理员添加委托公司时需要选择第三方机构
        if($this->user_auth['role']==1){
            $zbuilder->addSelect('company_type', '公司类型', '<span class="text-danger">必选</span>', $company_type);
            $third_company=CompanyModel::where('company_type','third')->column('name','id');//第三方机构
            $zbuilder->addSelect('b_company', '所属第三方检测机构','<span class="text-danger">必选</span>',$third_company)
                     ->setTrigger('company_type', 'third_slave', 'b_company');
        }
        $zbuilder->addFormItem('text','description','公司详细描述');
        return  $zbuilder->setFormData($info)->fetch();
    }

    //删除公司
    public function company_del(){
        if($this->user_auth['role']!==1&&$this->user_auth['company_id']!==0){
            $this->error('无权操作');
        }
        $id=$this->request->param('id');
        $has_company=CompanyModel::where('id',$id)->find();
        if(!$has_company){
            $this->error('未找到公司');
        }
        $has_user=User::where('company_id',$id)->count(1);
        if($has_user){
            $this->error('公司已有用户无法删除');
        }
        $has_business=BusinessModel::where("company_id",$id)->count(1);
        if($has_business){
            $this->error('公司已有业务无法删除');
        }
        $has_equipment=EquipmentModel::where("company_id",$id)->count(1);
        if($has_equipment){
            $this->error('公司存在已添加设备,无法删除');
        }
        $del_result=CompanyModel::where("id",$id)->delete();
        if(!$del_result){
            $this->error('删除失败');
        }
        action_log('company_del', 'company', $id, UID, json_encode($has_company,JSON_UNESCAPED_UNICODE));
        $this->success('删除公司成功');

    }




}